package com.cn.qtms.controller;

import com.cn.qtms.common.result.Result;
import com.cn.qtms.common.result.ResultUtil;
import com.cn.qtms.entity.TsAttachment;
import com.cn.qtms.util.IdWorker;
import com.cn.qtms.util.oss.AliyunOssUtil;
import com.cn.qtms.entity.vo.AttachmentVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;

/**
 * @Name:OssController
 * @Description:Oss相关操作接口
 * @Author: Neil
 * @Date: 2019-08-09 11:13
 **/
@Controller
@Api(tags = "OssController")
@RequestMapping("/aliyun/oss")
public class OssController {

    @Autowired
    private AliyunOssUtil util;

    @ApiOperation(value = "oss上传")
    @RequestMapping(value = "upload",method = RequestMethod.POST)
    @ResponseBody
    public Result<AttachmentVo> upload(@RequestParam(value="file") MultipartFile file){
        try {
            if(null != file){
                String filename = file.getOriginalFilename();
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    String uploadUrl = "https://threshzy.oss-cn-shanghai.aliyuncs.com/"+ util.upload(newFile);
                    newFile.delete();
                    return ResultUtil.success(new AttachmentVo(new IdWorker().nextId(),true,filename,uploadUrl));
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return ResultUtil.error();
    }

    @RequestMapping(value = "remove",method = RequestMethod.POST)
    @ResponseBody
    public Result<AttachmentVo> remove(@RequestBody HashMap<String,String> request){
        //删除本地数据库村存储的而文件信息
        try{
            TsAttachment attachment=new TsAttachment();
            return ResultUtil.success(new AttachmentVo(attachment.getId(),true,attachment.getOriginalName(),attachment.getFileName()));
        }catch (Exception ex){
            return ResultUtil.error(400,"路径有误，删除失败");
        }
    }
}
